package com.ds.infra.rpc.core.invoke;

/**
 * 作用：Netty客户端连接池管理
 *
 * @author WeiShaoying
 */
import com.ds.infra.rpc.core.transport.client.NettyClient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NettyClientPool {

    /**
     * 客户端池，用于缓存已经创建的NettyClient实例
     * key: 主机地址和端口号拼接成的字符串
     * value: 对应的NettyClient实例
     */
    private final Map<String, NettyClient> clientMap = new ConcurrentHashMap<>();

    public NettyClient getClient(String host, int port) {
        String key = host + ":" + port;
        return clientMap.computeIfAbsent(key, k -> {
            NettyClient client = new NettyClient(host, port);
            client.connect();
            return client;
        });
    }

    public void shutdown() {
        clientMap.values().forEach(NettyClient::shutdown);
    }
}
